"""应用配置管理"""

import os
from functools import lru_cache
from typing import List, Optional

from pydantic_settings import BaseSettings
from pydantic import Field, validator


class Settings(BaseSettings):
    """应用配置类"""

    # 应用基础配置
    app_name: str = Field(default="Medical Report API", description="应用名称")
    app_version: str = Field(default="1.0.0", description="应用版本")
    app_env: str = Field(default="development", description="应用环境")
    debug: bool = Field(default=False, description="调试模式")

    # 服务器配置
    host: str = Field(default="0.0.0.0", description="服务器绑定地址")
    port: int = Field(default=8000, description="服务器端口")
    reload: bool = Field(default=False, description="热重载模式")

    # 数据库配置
    database_url: str = Field(default="sqlite:///./medical_reports.db", description="数据库连接URL")

    # Redis配置
    redis_url: str = Field(default="redis://localhost:6379/0", description="Redis连接URL")

    # 安全配置
    secret_key: str = Field(default="your-secret-key-here", description="JWT密钥")
    algorithm: str = Field(default="HS256", description="JWT算法")
    access_token_expire_minutes: int = Field(default=30, description="访问令牌过期时间")

    # 日志配置
    log_level: str = Field(default="INFO", description="日志级别")
    log_format: str = Field(default="json", description="日志格式")

    # 医院配置
    hospital_id: str = Field(default="001", description="医院ID")
    hospital_name: str = Field(default="测试医院", description="医院名称")

    # 接口限流
    rate_limit: int = Field(default=100, description="限流次数")
    rate_limit_period: int = Field(default=60, description="限流时间窗口(秒)")

    # 跨域配置
    cors_origins: List[str] = Field(default=["*"], description="CORS允许源")
    cors_allow_credentials: bool = Field(default=True, description="CORS允许凭证")
    cors_allow_methods: List[str] = Field(default=["*"], description="CORS允许方法")
    cors_allow_headers: List[str] = Field(default=["*"], description="CORS允许头")

    @validator("cors_origins", pre=True)
    def parse_cors_origins(cls, v):
        """解析CORS源配置"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v

    @validator("cors_allow_methods", pre=True)
    def parse_cors_methods(cls, v):
        """解析CORS方法配置"""
        if isinstance(v, str):
            return [method.strip() for method in v.split(",")]
        return v

    @validator("cors_allow_headers", pre=True)
    def parse_cors_headers(cls, v):
        """解析CORS头配置"""
        if isinstance(v, str):
            return [header.strip() for header in v.split(",")]
        return v

    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.app_env == "development"

    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self.app_env == "production"

    @property
    def is_testing(self) -> bool:
        """是否为测试环境"""
        return self.app_env == "testing"

    class Config:
        """Pydantic配置"""
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False


@lru_cache()
def get_settings() -> Settings:
    """获取应用配置（单例模式）"""
    return Settings()


# 全局配置实例
settings = get_settings()